package com.itheima.htmo_01.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.htmo_01.dto.QuestionsDTO;
import com.itheima.htmo_01.dto.QuestionsPageDTO;
import com.itheima.htmo_01.exception.BusinessException;
import com.itheima.htmo_01.mapper.QuestionsMapper;
import com.itheima.htmo_01.pojo.Questions;
import com.itheima.htmo_01.pojo.User;
import com.itheima.htmo_01.service.QuestionsService;
import com.itheima.htmo_01.service.UserService;
import com.itheima.htmo_01.utils.ThreadLocalUtil;
import com.itheima.htmo_01.vo.QuestionsPageVO;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class QuestionsServiceImpl extends ServiceImpl<QuestionsMapper,Questions> implements QuestionsService {

    @Resource
    private UserService userService;

    @Override
    public void saveQuestion(QuestionsDTO questionsDTO) {

        Questions questions = new Questions();
        questions.setDescription(questionsDTO.getDescription());
        questions.setTitle(questionsDTO.getTitle());
        questions.setImageIds(questionsDTO.getImageIds());


        // 校验参数
        checkParams(questions);

        // 初化参数
        initParams(questions);

        save(questions);

    }


    @Override
    public Page<QuestionsPageVO> getPage(QuestionsPageDTO questionsPageDTO) {

        if(ObjectUtil.isEmpty(questionsPageDTO.getPageNo())){
            questionsPageDTO.setPageNo(1);
        }

        if(ObjectUtil.isEmpty(questionsPageDTO.getPageSize())){
            questionsPageDTO.setPageSize(10);
        }
        // 分页查询对象
        Page<Questions> page = new Page<>(questionsPageDTO.getPageNo(), questionsPageDTO.getPageSize());

        // 条件
        LambdaQueryWrapper<Questions> condition = new LambdaQueryWrapper<Questions>()
                .eq(ObjectUtil.isNotEmpty(questionsPageDTO.getKeyWord())
                , Questions::getTitle, questionsPageDTO.getKeyWord());

        // 分页查询
        Page<Questions> result = page(page, condition);

        Set<Long> userIdList = result.getRecords().stream().map(questions -> questions.getUserId()).collect(Collectors.toSet());

        Map<Long, User> userMap =
                userService.list(new LambdaQueryWrapper<User>().in(User::getId, userIdList)).stream()
                .collect(Collectors.toMap(User::getId, Function.identity()));
        //   .collect(Collectors.toMap(User::getId, User::getUsername));


        List<QuestionsPageVO> collect = result.getRecords().stream()
                .map(questions -> {

                    QuestionsPageVO bean = BeanUtil.toBean(questions, QuestionsPageVO.class);
                    User user = userMap.get(questions.getUserId());
                    bean.setUsername(user.getUsername());
                    bean.setAvatar(user.getAvatar());

                    return bean;


                })
                .collect(Collectors.toList());

        Page<QuestionsPageVO> resultPage = new Page<QuestionsPageVO>();

        resultPage.setSize(result.getSize());
        resultPage.setTotal(result.getTotal());
        resultPage.setCurrent(result.getCurrent());
        resultPage.setRecords(collect);

        // 调用分页查询方法
        return resultPage;
    }

    // 校验参数
    private void checkParams(Questions questions) {

        if(ObjectUtil.isEmpty(questions.getTitle())){
            throw new BusinessException(500,"title不能为空");
        }
    }

    /**
     *  初化参数
     * @param questions
     */
    private void initParams(Questions questions) {

        questions.setCreatTime(LocalDateTime.now());

        Map<String, Object> claims = ThreadLocalUtil.get();
        Long userId = Long.valueOf(claims.get("id").toString());
        questions.setUserId(userId);

    }
}
